package com.ruoyi.system.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysArtistProject;
import com.ruoyi.system.domain.SysUserProject;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.SysProject;
import com.ruoyi.system.service.ISysProjectService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 项目管理Service业务层处理
 * 
 * @author cooc
 * @date 2024-06-19
 */
@Service
public class SysProjectServiceImpl implements ISysProjectService 
{
    @Autowired
    private SysProjectMapper sysProjectMapper;

    @Autowired
    private SysUserProjectMapper sysUserProjectMapper;

    @Autowired
    private SysArtistProjectMapper sysArtistProjectMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    SysUserServiceImpl sysUserService;

    /**
     * 查询项目管理
     * 
     * @param id 项目管理主键
     * @return 项目管理
     */
    @Override
    public SysProject selectSysProjectById(Long id)
    {
        SysProject res = sysProjectMapper.selectSysProjectById(id);
        initAuthorIds(res);
        return res;
    }

    /**
     * 查询项目管理列表
     * 
     * @param sysProject 项目管理
     * @return 项目管理
     */
    @Override
    public List<SysProject> selectSysProjectList(SysProject sysProject)

    {
        List<SysProject>  res = sysProjectMapper.selectSysProjectList(sysProject);
        for (SysProject item:res){
            initAuthorIds(item);
        }
        return res;
    }
    @Override
    public List<SysProject> selectSysProjectList(SysProject sysProject,Long userId)
    {

        List<SysProject> all = sysProjectMapper.selectSysProjectList(sysProject).stream().filter(item->item.getProjectStatus() !=SysProject.PROJECT_STATUS_DISABLE).collect(Collectors.toList());
        if(!all.isEmpty()){
            for (SysProject item:all){
                initAuthorIds(item);
            }
            return filterProjectsByAuthorID(all,userId);
        }
        return all;

    }

    /**
     * 新增项目管理
     * 
     * @param sysProject 项目管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSysProject(SysProject sysProject)
    {
        sysProject.setCreateTime(DateUtils.getNowDate());
        sysProject.setCreateBy(SecurityUtils.getUsername());
        int row = sysProjectMapper.insertSysProject(sysProject);
        insertAuthorIds(sysProject);
        return row;
    }

    /**
     * 修改项目管理
     * 
     * @param sysProject 项目管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSysProject(SysProject sysProject)
    {
        sysProject.setUpdateTime(DateUtils.getNowDate());
        insertAuthorIds(sysProject);
        updateProjectString(sysProject);
        return sysProjectMapper.updateSysProject(sysProject);
    }

    @Override
    @Transactional
    public int updateSysProjectInfo(SysProject sysProject) {
        updateProjectString(sysProject);
        return sysProjectMapper.updateSysProject(sysProject);
    }

    /**
     * 批量删除项目管理
     * 
     * @param ids 需要删除的项目管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteSysProjectByIds(Long[] ids)
    {
        //删除关联信息
        sysUserProjectMapper.deleteSysUserProjectByProjectIds(ids);
        sysArtistProjectMapper.deleteSysArtistProjectByProjectIds(ids);
        return sysProjectMapper.deleteSysProjectByIds(ids);
    }

    /**
     * 删除项目管理信息
     * 
     * @param id 项目管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteSysProjectById(Long id)
    {
        sysUserProjectMapper.deleteSysUserProjectByProjectId(id);
        sysArtistProjectMapper.deleteSysArtistProjectByProjectId(id);
        return sysProjectMapper.deleteSysProjectById(id);
    }

    @Transactional
    private void insertAuthorIds(SysProject sysProject){
        //先删关系
        deleteAuthorIds(sysProject);
        Long[] ids = sysProject.getAuthorIds();
        List<Long> all = initMangerAuthorIds(sysProject);
        List<Long> res = Stream.concat(Arrays.stream(ids),all.stream()).distinct().collect(Collectors.toList());
        if(!res.isEmpty()){
            for (Long id : res){
                SysUserProject sysUserProject = new SysUserProject(id,sysProject.getId());
                sysUserProjectMapper.insertSysUserProject(sysUserProject);
            }
        }
    }

    private List<Long> initMangerAuthorIds(SysProject sysProject){
        SysRole manager = sysRoleMapper.selectRoleByRoleKey("@systemAdmin");
        List<Long> mangerAuthorIds = sysUserRoleMapper.selectUserRoleByRoleId(manager.getRoleId()).stream()
                .map(item->item.getUserId()).collect(Collectors.toList());
        mangerAuthorIds.add(SecurityUtils.getUserId());
        return mangerAuthorIds;
    }
    
    private void deleteAuthorIds(SysProject sysProject){
        sysUserProjectMapper.deleteSysUserProjectByProjectId(sysProject.getId());
    }

    private void initAuthorIds(SysProject sysProject){
        List<SysUserProject> list = sysUserProjectMapper.selectSysUserProjectByProjectId(sysProject.getId());
        List<Long> ids = list.stream().map(SysUserProject::getUserId).filter(userID -> !sysUserService.checkUserIsDel(userID) && !sysUserService.checkUserIsManager(userID)).collect(Collectors.toList());
        sysProject.setAuthorIds(ids.toArray(new Long[0]));
    }

    private List<SysProject> filterProjectsByAuthorID(List<SysProject> all,Long authorId){
        List<Long> projectIds = sysUserProjectMapper.selectSysUserProjectByAuthorId(authorId).stream().map(SysUserProject::getProjectId).collect(Collectors.toList());
        return all.stream().filter(p-> projectIds.contains(p.getId()) || p.getCreateBy().equals(sysUserMapper.selectUserById(authorId).getUserName())).collect(Collectors.toList());
    }

    @Transactional
    private void updateProjectString(SysProject sysProject){
        //查询关联表的项目数据
        List<SysArtistProject> sysArtistProjects = sysArtistProjectMapper.selectSysArtistProjectByProjectId(sysProject.getId());
        //比较项目维度和自定义字段数据
        if(!sysArtistProjects.isEmpty()){
            for (SysArtistProject item:sysArtistProjects){
                if(sysProject.getProjectScore()!=null && item.getProjectScore()!=null){
                    String score_string = checkStringValue(item.getProjectScore(), sysProject.getProjectScore());
                    item.setProjectScore(score_string);
                }else if(sysProject.getProjectScore()!=null){
                    item.setProjectScore(sysProject.getProjectScore());
                }
                if(sysProject.getProjectInfo()!=null &&item.getProjectInfo()!=null){
                    String info_string = checkStringValue(item.getProjectInfo(), sysProject.getProjectInfo());
                    item.setProjectInfo(info_string);
                }else if(sysProject.getProjectInfo()!=null){
                    item.setProjectInfo(sysProject.getProjectInfo());
                }
                sysArtistProjectMapper.updateSysArtistProject(item);
            }
        }

        //
    }

    /**
     *
     * @param src 原始数据
     * @param dst 新标准数据
     */
    private String checkStringValue(String src,String dst){
        JSONArray src_json = JSON.parseArray(src);
        JSONArray dst_json = JSON.parseArray(dst);
        if(!dst_json.isEmpty()){
            for (Object dst_item:dst_json){
               JSONObject dst_obj = (JSONObject) dst_item;
               for (Object src_item:src_json){
                   JSONObject src_obj = (JSONObject) src_item;
                   if(dst_obj.get("key").equals(src_obj.get("key"))){
                       dst_obj.put("value",src_obj.get("value"));
                       break;
                   }
               }
            }
            return JSON.toJSONString(dst_json);
        }
        //如果新标准数据为空，就同步清空关联的原始数据
        return "[]";
    }
}
